<?php

namespace App\Http\Controllers;

use App\Models\CopyDataResource;
use App\Models\Device;
use App\Models\ManagerLog;
use DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Validator;
use App\Models\DataResource;
use App\Models\AlipayDataResource;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Models\Fans;

class DataResourceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $totalCount = DataResource::count();
        $usedCount = DataResource::where('is_used', true)->count();
        $registeredCount = DataResource::where('is_registered_wechat', true)->count();
        if($request->account){
            $dataResource = DataResource::where('account',$request->account)->paginate(10)->toArray();
//        $dataResource = DataResource::where('account','like','%'. $request->account .'%')->paginate(10)->toArray();
        }else{
            $dataResource = DataResource::paginate(10)->toArray();
        }
        $dataResource['totalCount'] = $totalCount;
        $dataResource['usedCount'] = $usedCount;
        $dataResource['registeredCount'] = $registeredCount;
        return $this->success(0, '', $dataResource);
    }
    public function copyIndex(Request $request)
    {
        if($request->id){
            CopyDataResource::find($request->id)->delete();
        }
        $totalCount = CopyDataResource::count();
        $usedCount = CopyDataResource::where('is_used', true)->count();
        $registeredCount = CopyDataResource::where('is_registered_copy', true)->count();
        if($request->account){
            $dataResource = CopyDataResource::where('account',$request->account)->paginate(10)->toArray();
//        $dataResource = CopyDataResource::where('account','like','%'. $request->account .'%')->paginate(10)->toArray();
        }else{
            $dataResource = CopyDataResource::paginate(10)->toArray();
        }
        $dataResource['totalCount'] = $totalCount;
        $dataResource['usedCount'] = $usedCount;
        $dataResource['registeredCount'] = $registeredCount;
        return $this->success(0, '', $dataResource);
    }

    public function alipayIndex(Request $request)
    {
        $totalCount = AlipayDataResource::count();
        $usedCount = AlipayDataResource::where('is_used', true)->count();
        $maleCount = AlipayDataResource::where('sex','1')->count();
        $femaleCount = AlipayDataResource::where('sex','0')->count();
        if($request->phone){
            $dataResource = AlipayDataResource::where('phone',$request->phone)->paginate(10)->toArray();
//        $dataResource = AlipayDataResource::where('account','like','%'. $request->account .'%')->paginate(10)->toArray();
        }else{
            $dataResource = AlipayDataResource::paginate(10)->toArray();
        }
        $dataResource['totalCount'] = $totalCount;
        $dataResource['usedCount'] = $usedCount;
        $dataResource['maleCount'] = $maleCount;
        $dataResource['femaleCount'] = $femaleCount;
        return $this->success(0, '', $dataResource);
    }

    public function getOne(Request $request)
    {
        if($request->count > 0){
            $count = $request->count;
        }else{
            $count = 1;
        }
        $data = [];
        $num=0;
        $head = DataResource::where('is_used',1)->orderBy('id','desc')->first();
        if($head){
            $line = $head->id;
        }else{
            $line = 0;
        }
        $row = DB::update('UPDATE  data_resources SET is_used="1", id=LAST_INSERT_ID(id) WHERE is_used="0" LIMIT ?',[$count]);
        if(!$row){
            return $this->failure(-1, 'no data');
        }
        $query = DB::select('SELECT * FROM data_resources WHERE ROW_COUNT()>0 and id=LAST_INSERT_ID();');
        $id = $query[0]->id - $count;
        $fans1 = DataResource::where('id','>',$line)
            ->orderBy('id')->select('account')->limit($count)->get();
        $fans2 = DataResource::where('id','>',$id)
            ->orderBy('id')->select('account')->limit($count)->get();
        if($id != $line){
            if(count($fans1) != $count){
                $fans = $fans1;
            }else{
                $fans = $fans2;
            }
        }else{
            $fans = $fans2;
        }
        if($fans){
            foreach ($fans as $fan) {
                $data[$num] = $fan->account;
                $num++;
            }
            if($request->imei){
                $device = Device::where('imei',$request->imei)->first();
                if($device){
                    $this->deviceDetailedList($type=2,$detail_type=8,$device->id);
                }
            }
            return $data;
        }
    }

    public function getCopy(Request $request)
    {
        if($request->count > 0){
            $count = $request->count;
        }else{
            $count = 1;
        }
        $data = [];
        $num=0;
        $head = CopyDataResource::where('is_used',1)->orderBy('id','desc')->first();
        if($head){
            $line = $head->id;
        }else{
            $line = 0;
        }
        $row = DB::update('UPDATE  copy_data_resources SET is_used="1", id=LAST_INSERT_ID(id) WHERE is_used="0" LIMIT ?',[$count]);
        if(!$row){
            return $this->failure(-1, 'no data');
        }
        $query = DB::select('SELECT * FROM copy_data_resources WHERE ROW_COUNT()>0 and id=LAST_INSERT_ID();');
        $id = $query[0]->id - $count;
        $fans1 = CopyDataResource::where('id','>',$line)
            ->orderBy('id')->select('account')->limit($count)->get();
        $fans2 = CopyDataResource::where('id','>',$id)
            ->orderBy('id')->select('account')->limit($count)->get();
        if($id != $line){
            if(count($fans1) != $count){
                $fans = $fans1;
            }else{
                $fans = $fans2;
            }
        }else{
            $fans = $fans2;
        }
        if($fans){
            foreach ($fans as $fan) {
                $data[$num] = $fan->account;
                $num++;
            }
            /*if($request->imei){
                $device = Device::where('imei',$request->imei)->first();
                if($device){
                    $this->deviceDetailedList($type=2,$detail_type=8,$device->id);
                }
            }*/
            return $data;
        }
    }

    public function getAlipay(Request $request)
    {
        if($request->count > 0){
            $count = $request->count;
        }else{
            $count = 1;
        }
        $data = [];
        $num=0;
        $head = AlipayDataResource::where('is_used',1)->orderBy('id','desc')->first();
        if($head){
            $line = $head->id;
        }else{
            $line = 0;
        }
        $row = DB::update('UPDATE  alipay_data_resources SET is_used="1", id=LAST_INSERT_ID(id) WHERE is_used="0" LIMIT ?',[$count]);
        if(!$row){
            return $this->failure(-1, 'no data');
        }
        $query = DB::select('SELECT * FROM alipay_data_resources WHERE ROW_COUNT()>0 and id=LAST_INSERT_ID();');
        $id = $query[0]->id - $count;
        $fans1 = AlipayDataResource::where('id','>',$line)
            ->orderBy('id')->select('phone')->limit($count)->get();
        $fans2 = AlipayDataResource::where('id','>',$id)
            ->orderBy('id')->select('phone')->limit($count)->get();
        if($id != $line){
            if(count($fans1) != $count){
                $fans = $fans1;
            }else{
                $fans = $fans2;
            }
        }else{
            $fans = $fans2;
        }
        if($fans){
            foreach ($fans as $fan) {
                $data[$num] = $fan->phone;
                $num++;
            }
            if($request->imei){
                $device = Device::where('imei',$request->imei)->first();
                if($device){
                    $this->deviceDetailedList($type=2,$detail_type=9,$device->id);
                }
            }
            return $data;
        }
    }

    public function setRegistered(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'data' => 'required',
            'is_wechat' => 'required|numeric|max:2,min:0',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $fans = json_decode($request->data,true);
        if($fans){
            $date = date('Y-m-d');
            $filename =  $date . '-PASS.txt';
            $name="txt/".iconv("UTF-8","gb2312", $filename);
            if(!is_dir("txt"))    //判断文件夹是否存在,否则创建
            {
                mkdir("txt",0755);
            }
            if($request->is_wechat == 1){
                foreach ($fans as $fan) {
                    if($fan){
                        DB::update('UPDATE  data_resources SET is_registered_wechat="1" WHERE account=?',[$fan]);
                        file_put_contents($name,$fan."\r\n", FILE_APPEND);
                    }
                }
            }else{
                foreach ($fans as $fan) {
                    if($fan){
                        $data = DataResource::where('account',$fan)->first();
                        $data->is_registered_wechat = $request->is_wechat;
                        $data->save();
                    }
                }
            }
        }
        return $this->success(0, '更新成功');
    }

    public function setAlipayName(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'data' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $fans = json_decode($request->data,true);
        if($fans){
            $date = date('Y-m-d');
            $filename =  $date . '-AlipayPASS.txt';
            $name="txt/".iconv("UTF-8","gb2312", $filename);
            if(!is_dir("txt"))    //判断文件夹是否存在,否则创建
            {
                mkdir("txt",0755);
            }
            //另一个地址另存一份
            $handleName="handleTxt/".iconv("UTF-8","gb2312", $filename);
            if(!is_dir("handleTxt"))    //判断文件夹是否存在,否则创建
            {
                mkdir("handleTxt",0755);
            }
            foreach ($fans as $fan) {
                if(isset($fan[1])){
                    if($fan[1] == 1){
                        switch ($fan[3]){
                            case '0': $sex = '女';break;
                            case '1': $sex = '男';break;
                            case '2': $sex = '未知';break;
                            default: $sex = '未知';break;
                        }
                        $data = AlipayDataResource::where('phone',$fan[0])->first();
                        if($data) {
                            $data->is_exists = $fan[1];
                            $data->alipay_name = $fan[2];
                            $data->sex = $fan[3];
                        }else if($request->add){
                            $data = AlipayDataResource::create([
                                'phone'=>$fan[0],
                                'is_exists'=>$fan[1],
                                'alipay_name'=>$fan[2],
                                'sex'=>$fan[3],
                                'is_used'=>1
                            ]);
                        }else{
                            return $this->failure(-1, '无此数据:'.$fan[0]);
                        }
                        if($fan[3] == '3'){
                            $data->is_used = 0;
                        }else{
                            file_put_contents($name,$fan[0]."----".$fan[2]."----".$sex."\r\n", FILE_APPEND);
                            file_put_contents($handleName,$fan[0]."----".$fan[2]."----".$sex."\r\n", FILE_APPEND);//另存
                        }
                        $data->save();
                    }
                }
            }
            return $this->success(0, '更新成功');
        }
        return false;
    }
    public function setCopy(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'data' => 'required',
            'is_copy' => 'required|numeric|max:2,min:0',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $fans = json_decode($request->data,true);
        if($fans){
            $date = date('Y-m-d');
            if($request->is_copy == 1){
                $filename =  $date . '-Alipay.txt';
                $name="CopyTxt/".iconv("UTF-8","gb2312", $filename);
                if(!is_dir("CopyTxt"))    //判断文件夹是否存在,否则创建
                {
                    mkdir("CopyTxt",0755);
                }
                foreach ($fans as $fan) {
                    try{
                        if(CopyDataResource::where('account',$fan)->first()->is_registered_copy === 2){
                            file_put_contents($name,$fan."\r\n", FILE_APPEND);
                            DB::update('UPDATE  copy_data_resources SET is_registered_copy="1" WHERE account=?',[$fan]);
                        }
                    }catch (\Exception $e){
                        Log::info($e->getMessage());
                    }
                }
            }else{
                foreach ($fans as $fan) {
                    $data = CopyDataResource::where('account',$fan)->first();
                    try{
                        $data->is_registered_copy = $request->is_copy;
                        $data->save();
                    }catch (\Exception $e){
                        Log::info($e->getMessage());
                    }
                }
            }
        }
        return $this->success(0, '更新成功');
    }
    public function cacheAlipay(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'data' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $alipay = json_decode($request->data,true);
        if($alipay){
            $date = date('Y-m-d');
            $filename =  $date . '-AlipayPASS(name).txt';
            $name="AlipayCacheTxt/".iconv("UTF-8","gb2312", $filename);
            if(!is_dir("AlipayCacheTxt"))    //判断文件夹是否存在,否则创建
            {
                mkdir("AlipayCacheTxt",0755);
            }
            foreach ($alipay as $fan) {
                file_put_contents($name,$fan[0]."----".$fan[1]."\r\n", FILE_APPEND);
            }
        }
        return $this->success(0, '转存成功');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,$id)
    {
        if($request->type == 2){
            AlipayDataResource::destroy($id);
        }else{
            DataResource::destroy($id);
        }
        return $this->success(0, '删除成功');
    }

    public function deleteAll(Request $request)
    {
        if($request->type == 2){
            AlipayDataResource::truncate();
        }else{
            DataResource::truncate();
        }
        return $this->success(0, '删除成功');
    }
    public function deleteAllCopy(Request $request)
    {
        CopyDataResource::truncate();
        return $this->success(0, '删除成功');
    }

    public function batchRemove(Request $request)
    {
        $ids = explode(',', $request->ids);
        DataResource::destroy($ids);
        return $this->success(0, '删除成功');
    }

    public function batchUpload(Request $request)
    {
        if ($request->hasFile('dataResource')) {
            $filename = 'dataResource';
        }else{
            $filename = 'alipayDataResource';
        }
        if ($request->file($filename)->isValid()) {
            $path = $request->file($filename)->store($filename);
            $storagePath  = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
            $file = $storagePath . $path;
            $contents = preg_replace('# #','',file_get_contents($file));
            file_put_contents($file, $contents);
            if($filename == 'dataResource'){
                $query = "LOAD DATA LOCAL INFILE '" . $file . "'
    INTO TABLE data_resources 
    LINES TERMINATED BY '\r\n'
        (account,
        @is_used,
        @is_registered_wechat,
        @created_at,
        @updated_at)
SET is_used=0,is_registered_wechat=2,created_at=NOW(),updated_at=NOW()";
            }else{
                $query = "LOAD DATA LOCAL INFILE '" . $file . "'
    INTO TABLE alipay_data_resources 
    LINES TERMINATED BY '\r\n'
        (phone,
        @is_exists,
        @alipay_name,
        @sex,
        @is_used,
        @created_at,
        @updated_at)
SET is_exists=2,alipay_name='',sex='2',is_used=0,created_at=NOW(),updated_at=NOW()";
            }
            DB::connection()->getpdo()->exec($query);
            return $this->success(0, '上传成功！');
        }
        return $this->failure(-1, '没有上传任何文件！');
    }

    public function batchUploadCopy(Request $request)
    {
        if ($request->hasFile('CopyDataResource')) {
            $filename = 'CopyDataResource';
            if ($request->file($filename)->isValid()) {
                $path = $request->file($filename)->store($filename);
                $storagePath  = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
                $file = $storagePath . $path;
                $contents = preg_replace('# #','',file_get_contents($file));
                file_put_contents($file, $contents);
                if($filename == 'CopyDataResource'){
                    $query = "LOAD DATA LOCAL INFILE '" . $file . "'
    INTO TABLE copy_data_resources 
    LINES TERMINATED BY '\r\n'
        (account,
        @is_used,
        @is_registered_copy,
        @created_at,
        @updated_at)
SET is_used=0,is_registered_copy=2,created_at=NOW(),updated_at=NOW()";
                }
                DB::connection()->getpdo()->exec($query);
                return $this->success(0, '上传成功！');
            }
        }
        return $this->failure(-1, '没有上传任何文件！');
    }

  public function export(Request $request)
  {
      if($request->token == '' || Cache::pull('pin'.$request->token) != $request->token) return 404;
      if($request->type == 1){//微信
          $date = date('Y年m月d日');
          $fans = DataResource::where('is_registered_wechat', 1)
              ->get(['account','is_registered_wechat'])
              ->toArray();
          $filename = '微信加工数据(已注册)-' . $date . '.txt';
          $encoded_filename = urlencode($filename);
          $encoded_filename = str_replace("+", "%20", $encoded_filename);
          header("Content-Type: application/octet-stream");
          if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
              header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
          } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
              header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
          } else {
              header('Content-Disposition: attachment; filename="' . $filename . '"');
          }
          foreach ($fans as $fan) {
              echo $fan['account'] . '----' . ($fan['is_registered_wechat'] ? '已开通' : '未开通') . "\r\n";
          }
          /*$is_registered_wechat = $request->is_registered_wechat;
    $ext = '所有';

    if ($is_registered_wechat != -1) {
      if ($is_registered_wechat == 1) {
        $ext = '已开通微信';
      } else {
        $ext = '未开通微信';
      }
      $fans = DataResource::where(['is_registered_wechat' => $is_registered_wechat])->get();
    } else {
      $fans = DataResource::all()->toArray();
    }
    $filename = '数据源-' . $ext . '.txt';
    $encoded_filename = urlencode($filename);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);
    header("Content-Type: application/octet-stream");
    if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
      header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
    } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
      header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
    } else {
      header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    foreach ($fans as $fan) {
      echo $fan['account'] . '----' . ($fan['is_registered_wechat'] ? '已开通' : '未开通') . "\r\n";
    }*/
      }else if($request->type == 2){//支付宝
          $sex = $request->sex;
          $ext = '所有';
          $date = date('Y年m月d日');
          if($sex == 0){$ext = '女';}
          if($sex == 1){$ext = '男';}
          $type_name = '支付宝';
          if($sex == -1){
              if($request->exist) {
                  $fans = AlipayDataResource::where('is_exists', 1)->get();
              }else{
                  $fans = AlipayDataResource::where('is_exists', 0)->get();
              }
          }else{
              $fans = AlipayDataResource::where('is_exists', 1)->where('sex', $sex)->get();
          }
          $filename = '支付宝加工数据-' . $date . $type_name . '-' . $ext . '.txt';
          $encoded_filename = urlencode($filename);
          $encoded_filename = str_replace("+", "%20", $encoded_filename);
          header("Content-Type: application/octet-stream");
          if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
              header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
          } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
              header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
          } else {
              header('Content-Disposition: attachment; filename="' . $filename . '"');
          }
          foreach ($fans as $fan) {
              if($fan['sex'] == 1) {
                  $sex = '男';
              } elseif($fan['sex'] == 0) {
                  $sex = '女';
              } else {
                  $sex = '未知';
              }
              echo $fan['phone'] . '----' . $fan['alipay_name'] . '----' . $sex . "\r\n";
          }
      }
  }

    public static function exportCopy(Request $request)
    {
        if($request->token == '' || Cache::pull('pin'.$request->token) != $request->token) return 404;
        if($request->type == 'copy'){
            $date = date('Y年m月d日');
            $fans = CopyDataResource::where('is_registered_copy', 1)->get();
            $filename = '支付宝copy数据(已注册)-' . $date . '.txt';
            $encoded_filename = urlencode($filename);
            $encoded_filename = str_replace("+", "%20", $encoded_filename);
            header("Content-Type: application/octet-stream");
            if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
                header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
            } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
                header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $filename . '"');
            }
            foreach ($fans as $fan) {
                echo $fan['account'] . "\r\n";
            }
        }
    }

}
